package com.itboye.hutouben.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.hutouben.R;
import com.itboye.hutouben.activity.store.GoodDetailActivity;
import com.itboye.hutouben.activity.store.ShopCartActivity;
import com.itboye.hutouben.bean.GouWuCheBean;
import com.itboye.hutouben.presenter.OrderPresenter;
import com.itboye.hutouben.util.ByAlert;
import com.itboye.hutouben.util.Const;
import com.itboye.hutouben.util.IsUtilUid;
import com.itboye.hutouben.util.MyGongJv;
import com.itboye.hutouben.util.SPUtils;
import com.itboye.hutouben.util.XImageLoader;
import com.itboye.hutouben.volley.ResultEntity;

import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 购物车
 */
public class ShopCartAdapter extends BaseAdapter implements Observer {
    List<GouWuCheBean> list;
    Activity activity;
    CheckBoxInterface checkInterface;//复选框接口
    private ModifyCountInterface modifyCountInterface;//加或减接口

    OrderPresenter presenter;
    private Dialog dialog;// 自定义Dialog
    String id;
    double money;
    int tempCount = 0;

    public ShopCartAdapter(List<GouWuCheBean> list, Activity activity) {
        this.list = list;
        this.activity = activity;
        presenter = new OrderPresenter(this);
        showExtraDialog();
    }

    public void setCheckInterface(CheckBoxInterface checkInterface) {
        this.checkInterface = checkInterface;
    }

    public void setModifyCountInterface(ModifyCountInterface modifyCountInterface) {
        this.modifyCountInterface = modifyCountInterface;
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        return list == null ? 0 : list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(activity).inflate(R.layout.item_shopcart, null);
            viewHolder.gwc_box = (CheckBox) convertView.findViewById(R.id.gwc_box);
            viewHolder.gwc_img = (ImageView) convertView.findViewById(R.id.gwc_img);
            viewHolder.gwc_title = (TextView) convertView.findViewById(R.id.gwc_title);
            viewHolder.gwc_guige = (TextView) convertView.findViewById(R.id.gwc_guige);
            viewHolder.gwc_money = (TextView) convertView.findViewById(R.id.gwc_money);
            viewHolder.gwc_jian = (TextView) convertView.findViewById(R.id.gwc_jian);
            viewHolder.gwc_jia = (TextView) convertView.findViewById(R.id.gwc_jia);
            viewHolder.gwc_num = (EditText) convertView.findViewById(R.id.gwc_num);
            viewHolder.gwc_number = (TextView) convertView.findViewById(R.id.gwc_number);
            viewHolder.gwc_baocun = (ImageView) convertView.findViewById(R.id.gwc_baocun);
            viewHolder.gwc_delete = (ImageView) convertView.findViewById(R.id.gwc_delete);
            viewHolder.gwc_shixiao = (ImageView) convertView.findViewById(R.id.gwc_shixiao);
            //    viewHolder.gwc_yunfei = (TextView) convertView.findViewById(R.id.gwc_yunfei);
            viewHolder.gwc_xiugai = (ImageView) convertView.findViewById(R.id.gwc_xiugai);
            viewHolder.gwc_layout01 = (LinearLayout) convertView.findViewById(R.id.gwc_layout01);
            viewHolder.gwc_layout02 = (RelativeLayout) convertView.findViewById(R.id.gwc_layout02);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        XImageLoader.load(Const.IMAGE_HEAD + list.get(position).getIcon_url(),
                viewHolder.gwc_img);
        viewHolder.gwc_title.setText(list.get(position).getName());

        viewHolder.gwc_guige.setText(list.get(position).getSku_desc());
        viewHolder.gwc_money.setText("¥" + MyGongJv.zhuanhua(Double.parseDouble(list.get(position).getPrice()) / 100));
        viewHolder.gwc_num.setText(list.get(position).getCount() ==0?"":(list.get(position).getCount() + ""));
        viewHolder.gwc_box.setChecked(list.get(position).isSelected());
        viewHolder.gwc_number.setText("数量:" + list.get(position).getCount() + "");

        if (list.get(position).getItem_status().equals("1")) {
            viewHolder.gwc_box.setVisibility(View.VISIBLE);
            viewHolder.gwc_shixiao.setVisibility(View.GONE);
        } else {
            viewHolder.gwc_box.setVisibility(View.GONE);
            viewHolder.gwc_shixiao.setVisibility(View.VISIBLE);

        }
        if(list.get(position).isXiugai()){
            viewHolder.gwc_layout01.setVisibility(View.GONE);
            viewHolder.gwc_layout02.setVisibility(View.VISIBLE);
        }else{
            viewHolder.gwc_layout01.setVisibility(View.VISIBLE);
            viewHolder.gwc_layout02.setVisibility(View.GONE);
        }
        //点击标题跳转到详情
        viewHolder.gwc_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, GoodDetailActivity.class);
                intent.putExtra("goodsId", list.get(position).getP_id());
                intent.putExtra("goodsName", list.get(position).getName());
                activity.startActivity(intent);
            }
        });

        //删除
        viewHolder.gwc_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                id = list.get(position).getId();
                money = Double.parseDouble(list.get(position).getPrice()) / 100;
                dialog.show();
                viewHolder.gwc_layout01.setVisibility(View.VISIBLE);
                viewHolder.gwc_layout02.setVisibility(View.GONE);
            }
        });
        //box
        viewHolder.gwc_box.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckBox check = (CheckBox) v;
                viewHolder.gwc_box.setChecked(check.isChecked());
                checkInterface.checkChild(position, check.isChecked());// 暴露组选接口
            }
        });
        //减
        viewHolder.gwc_jian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyCountInterface.doDecrease(position, viewHolder.gwc_jia, viewHolder.gwc_box.isChecked(), "", viewHolder.gwc_num.getText().toString());
            }
        });
        //加
        viewHolder.gwc_jia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyCountInterface.doIncrease(position, viewHolder.gwc_jia, viewHolder.gwc_box.isChecked(), "", viewHolder.gwc_num.getText().toString());
            }
        });
        //修改
        viewHolder.gwc_xiugai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkInterface.xiugaiChild(position,!list.get(position).isXiugai());
            }
        });

        //保存
        viewHolder.gwc_baocun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(viewHolder.gwc_num.getText().toString().equals("")){
                    ByAlert.alert("请输入有效数量");
                    return;
                }
                if (list.get(position).getItem_status().equals("1")) {
                    list.get(position).setCount((int)Double.parseDouble(viewHolder.gwc_num.getText().toString()));
                    if(list.get(position).getCounts()==list.get(position).getCount()){
                    //    ByAlert.alert("没有操作");
                        checkInterface.xiugaiChild(position,!list.get(position).isXiugai());
                        return;
                    }

                    int oldNum = list.get(position).getCount();
                    int kc = Integer.parseInt(list.get(position).getQuantity());
                    int newNum = Integer.parseInt(viewHolder.gwc_num.getText().toString());
                    if (newNum > kc) {
                        ByAlert.alert("库存不足,剩余库存"+kc);
                        viewHolder.gwc_num.setText(kc+"");
                        return;
                    }

                    String uid = (String) SPUtils.get(activity, null, Const.ID, "");
                    presenter.updateGouWuChe(uid, list.get(position).getId(), viewHolder.gwc_num.getText().toString());
                    checkInterface.xiugaiChild(position,!list.get(position).isXiugai());
                    modifyCountInterface.onBaoCun(position, viewHolder.gwc_baocun, viewHolder.gwc_box.isChecked(), "", viewHolder.gwc_num.getText().toString());
                } else {
                    ByAlert.alert("商品已失效");
                    checkInterface.xiugaiChild(position,!list.get(position).isXiugai());
                }

            }
        });

        return convertView;
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            //删除成功
            if (entity.getEventType() == OrderPresenter.delete_success) {
                ByAlert.alert(entity.getData());
                dialog.dismiss();

                Iterator<GouWuCheBean> iterator = list.iterator();
                while (iterator.hasNext()) {
                    GouWuCheBean bean = iterator.next();
                    if (id.equals(bean.getId())) {
                        iterator.remove();
                        notifyDataSetChanged();
                        if (list.size() <= 0) {
                            ShopCartActivity.context.setGone();
                        }
                        ShopCartActivity.context.calculate();
                        ShopCartActivity.context.quanxuan();
                        break;
                    }
                }
            }
            if (entity.getEventType() == OrderPresenter.delete_fail) {
                ByAlert.alert(entity.getData());
                dialog.dismiss();
            }
            //更新成功
            if (entity.getEventType() == OrderPresenter.update_success) {
                ByAlert.alert(entity.getData());
                ShopCartActivity.context.calculate();
                ShopCartActivity.context.quanxuan();
            }
            if (entity.getEventType() == OrderPresenter.update_fail) {
                ByAlert.alert(entity.getData());
                ShopCartActivity.context.setVisible();
            }
        }
    }

    private String EVENT_TYPE_UNKNOWN = "_unknown";

    public ResultEntity handlerError(Object data) {
        ResultEntity result = (ResultEntity) data;
        if (result == null) {
            result = new ResultEntity("-1", "数据格式错误!~", data);
            return result;
        }

        if (result.hasError()) {
            ByAlert.alert(result.getMsg());
            result.setEventType(EVENT_TYPE_UNKNOWN);
            return result;
        }

        return result;
    }


    /**
     * 复选框的接口
     */
    public interface CheckBoxInterface {
        /**
         * 选框状态改变时触发的事件
         *
         * @param position  子元素位置
         * @param isChecked 子元素选中与否
         */
        public void checkChild(int position, boolean isChecked);

        /**
         * 修改
         * @param position
         * @param isChecked
         */
        public void xiugaiChild(int position, boolean isChecked);
    }

    /**
     * 改变数量的接口
     */
    public interface ModifyCountInterface {
        /**
         * 增加操作
         *
         * @param position      元素位置
         * @param showCountView 用于展示变化后数量的View
         * @param isChecked     子元素选中与否
         * @param num           数量
         */
        public void doIncrease(int position, View showCountView, boolean isChecked, String id, String num);

        /**
         * 删减操作
         *
         * @param position      子元素位置
         * @param showCountView 用于展示变化后数量的View
         * @param isChecked     子元素选中与否
         * @param num           数量
         */
        public void doDecrease(int position, View showCountView, boolean isChecked, String id, String num);

        /**
         * 保存操作
         *
         * @param position
         * @param showCountView
         * @param isChecked
         * @param id
         * @param num
         */
        public void onBaoCun(int position, View showCountView, boolean isChecked, String id, String num);

    }

    public class ViewHolder {
        ImageView gwc_img;
        CheckBox gwc_box;
        TextView gwc_title, gwc_guige, gwc_money, gwc_jian, gwc_jia, gwc_yunfei, gwc_number;
        EditText gwc_num;
        ImageView gwc_delete, gwc_baocun, gwc_shixiao;
        ImageView gwc_xiugai;
        LinearLayout gwc_layout01;
        RelativeLayout gwc_layout02;
    }

    /**
     * 删除Dialog
     */
    private void showExtraDialog() {
        dialog = new Dialog(activity, R.style.rel_dialog);
        View view = LayoutInflater.from(activity).inflate(
                R.layout.dialog_delete, null);
        dialog.setContentView(view);
        TextView dialog_ok = (TextView) view.findViewById(R.id.dialog_ok);
        TextView dialog_quxiao = (TextView) view.findViewById(R.id.dialog_quxiao);
        TextView user_title = (TextView) view.findViewById(R.id.user_title);
        user_title.setText("删除商品");
        TextView dialog_conext = (TextView) view.findViewById(R.id.dialog_conext);
        dialog_conext.setText("确定要删除该商品吗?");
        dialog.setCanceledOnTouchOutside(false);
        dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String uid = (String) SPUtils.get(activity, null, Const.ID, "");
                presenter.gouWuCheShanChu(uid, id);
            }
        });
        dialog_quxiao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        // 屏幕宽度
        int screenWidth = display.getWidth();
        // 屏幕高度
        int screenHeight = display.getHeight();
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        lp.width = screenWidth * 3 / 4;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }
}
